using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TouchSmart.Animations
{
    public class Animator : IAnimator
    {
        private const int Interval = 120;

        private readonly Control _control;
        private readonly Timer _timer;

        public List<AnimationMetadata> Animations { get; set; }

        public Animator(Control control)
        {
            this._control = control;

            this._timer = new Timer{Interval = Interval};
            this._timer.Tick += (s, e) => Animate();

            Animations = new List<AnimationMetadata>();
        }

        private void Animate()
        {
            if(Animations.Count == 0)
            {
                this._timer.Enabled = false;
                return;
            }

            var tick = Environment.TickCount;

            for (var i = 0; i < Animations.Count; i++)
            {
                var animationMetadata = Animations[i];

                if(animationMetadata.IsAnimationCompleted == false)
                {
                    animationMetadata.Animate(tick, Interval);
                }
                else
                {
                    Animations.RemoveAt(i);
                    i--;
                }
            }

            this._control.Invalidate();
            this._control.Update();
        }

        public void QueueAnimation(Animation animation)
        {
            var animationMetadata = new AnimationMetadata(Environment.TickCount, animation);
            this.Animations.Add(animationMetadata);

            this._timer.Enabled = true;
        }
    }
}